package com.zwy.stack.impl;

import com.zwy.stack.Stack;
//顺序栈
public class StackArray implements Stack {
    private final int LEN=10;  //数组默认大小
    private Object[] elements;
    private int top;

    //初始化栈
    public StackArray() {
        top=-1;
        elements=new Object[LEN];
    }

    @Override
    public int getSize() {
        return top+1;
    }

    @Override
    public boolean isEmpty() {
        return top<0;
    }

    @Override
    public void push(Object e) {
        if(getSize()>=elements.length)expandSpace();
        elements[++top]=e;
    }

    private void expandSpace(){
        Object[]a=new Object[elements.length*2];
        for (int i = 0; i < elements.length; i++) {
            a[i]=elements[i];
        }
        elements=a;
    }
    @Override
    public Object pop() throws Exception {
        if(getSize()<1){
            throw new StackOverflowError();
        }
        Object obj=elements[top];
        elements[top--]=null;
        return obj;
    }

    @Override
    public Object peek() throws Exception {
        if(getSize()<1){
            throw new StackOverflowError();
        }
        return elements[top];
    }
}
